package ycl.scheduled.common.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import ycl.scheduled.common.ApiResult;
import ycl.scheduled.common.constants.HtmlConstant;
import ycl.scheduled.common.constants.RedisConstant;
import ycl.scheduled.common.enums.ApiResultEnum;

import javax.annotation.Resource;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 * @author: YCL
 * @date: 2021-06-07 13:05:22
 */
@Component("authorizationConfig")
public class AuthorizationConfig implements HandlerInterceptor {

	@Resource
	private StringRedisTemplate stringRedisTemplate;


	/**
	 * 方法处理前执行
	 *
	 * @param request  请求
	 * @param response 响应
	 * @param handler  拦截器
	 * @return 返回 true 就可以继续执行, false 就无法执行目标接口
	 * @throws Exception 抛出最大异常
	 */
	@Override
	@SuppressWarnings("all")
	public boolean preHandle(
			@NotNull HttpServletRequest request,
			@NotNull HttpServletResponse response,
			@NotNull Object handler) throws Exception {
		String token = request.getHeader(HtmlConstant.TOKEN);
		if (StrUtil.isBlank(token)) {
			writeResponse(response, ApiResult.error(ApiResultEnum.NO_LOGIN.code, "未登录"));
			return false;
		}

		//在redis里查用户登录信息
		String key = RedisConstant.USER_LOGIN + token;
		String value = stringRedisTemplate.opsForValue().get(key);
		if (StrUtil.isBlank(value)) {
			writeResponse(response, ApiResult.error(ApiResultEnum.LOGIN_EXPIRED.code, "登录过期"));
			return false;
		}

		return true;
	}


	/**
	 * 返回响应
	 *
	 * @param response 响应体
	 * @param result 返回对象
	 * @throws IOException 抛流异常
	 */
	private void writeResponse(ServletResponse response, ApiResult<Object> result) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		try (PrintWriter writer = response.getWriter()) {
			writer.print(JSONObject.toJSONString(result));
		}
	}
}
